<template>
  <div class="product-center">
    <div class="product-left">
      <div class="product-left-center" :style="{height:height+'px'}">
          <Form
        ref="editForm"
        :model="form"
        :rules="diyData.rules"
        :label-width="100"
      >
      <FormItem label="商品名称：" prop="title">
          <Input
                  placeholder="请输入商品名称"
                  v-model="form.title"
                  style="width:420px"
                />
        </FormItem>
        <FormItem label="商品分类：" prop="typeId">
           <!-- <treeselect
           style="width: 200px"
              v-model="form.typeId"
              :options="apiData.producttypeList"
              placeholder="商品分类"
            /> -->

             <Select clearable
                style="width:200px;"
                v-model="form.typeId"
                placeholder="商品分类"
              >
             <Option v-for="(item,index) in apiData.producttypeList" :key="index" :value="item.id+''" :label="item.name">
              <div :class="item.level==2?'pdl10':''"><span v-if="item.level==2">————</span>{{item.name}}</div>
             </Option>
       
            </Select>
        </FormItem>
        <FormItem label="产品批号" prop="batchNum">
          <Input
                  placeholder="请输入产品批号"
                  v-model="form.batchNum"
                 style="width:420px"
                />
        </FormItem>
        <FormItem label="产品编号" prop="code">
          <Input
                  placeholder="请输入产品编号"
                  v-model="form.code"
                 style="width:420px"
                />
        </FormItem>
        <FormItem label="商品标签：" prop="tag">
          <Input
                  placeholder="请输入商品标签，不超过3个字"
                  v-model="form.tag"
                  maxlength="3"
                  style="width:210px"
                />
                <span v-for="(item,index) in apiData.productAllTag" :key="index" class="tag" @click="form.tag=item" v-if="item">{{item}}</span>
                <!-- <span class="tag" @click="form.tag='精品'">精品</span>
                <span class="tag" @click="form.tag='S级'">S级</span> -->
        </FormItem>
        <FormItem label="展示销量：" prop="showSales">
          <InputNumber :min="0"  placeholder="请输入展示销量"  v-model="form.showSales" style="width:210px" />
        </FormItem>
        <FormItem label="商品图片：" prop="img">
          <div class="upload-Img">
            <div v-for="(item,index) in form.img" :key="index" class="look-img">
              <img :src="item" style="width: 100%" />
              <div class="demo-upload-list-cover">
                <Icon
                  type="ios-eye-outline"
                  @click.native="lookFile(item)"
                ></Icon>
                <Icon
                  type="ios-trash-outline"
                  @click.native="deleteFile('img',index)"
                ></Icon>
              </div>
            </div>
            <template v-if="form.img.length < 5">
              <Upload
                :action="uploadUrl"
                :headers="headers"
                :on-error="uploadErr"
                :on-success="(value) => uploadSuccess('img', value)"
                name="file"
                :show-upload-list="false"
              >
                <div class="upload-btn">
                  <Icon
                    type="ios-cloud-upload"
                    size="52"
                    style="color: #3399ff"
                  ></Icon>
                  <p>上传图片</p>
                </div>
              </Upload>
            </template>
          </div>
        </FormItem>
        <FormItem label="商品视频：" prop="video">
          <div v-if="form.video">
              <video :src="form.video" style="width: 300px" controls/>
              <div class="demo-upload-list-cover">
                
                <Icon
                  type="ios-trash-outline"
                  size='24'
                  style="color: #3399ff;cursor:pointer"
                  @click.native="deleteFile('video')"
                ></Icon>
              </div>
            </div>
            <template v-else>
              <Upload
                :action="uploadUrl"
                :headers="headers"
                :on-error="uploadErr"
                :on-success="(value) => uploadSuccess('video', value)"
                name="file"
                :show-upload-list="false"
              >
                <div class="upload-btn">
                  <Icon
                    type="ios-cloud-upload"
                    size="52"
                    style="color: #3399ff"
                  ></Icon>
                  <p>上传视频</p>
                </div>
              </Upload>
            </template>
        </FormItem>
        <Divider plain ></Divider>
        <FormItem label="商品限购：" prop="imUrl">
            <i-switch size="large" true-value="1" false-value="0" v-model="form.limitEnabel">
                <span slot="open">开</span>
                <span slot="close">关</span>
            </i-switch>
            <span style="margin-left:20px;font-size:14px">每人限购：</span>
              <Input
                placeholder="数量"
                v-model="form.limitNumber"
                style="width:60px"
              />
             <span>件</span>
        </FormItem>
        <FormItem label="多规格：" prop="imUrl">
              <i-switch size="large" true-value="1" false-value="0" v-model="form.skuEnabel">
                <span slot="open">开</span>
                <span slot="close">关</span>
            </i-switch>
        </FormItem> 
        <template v-if="form.skuEnabel==1">
          <FormItem label="规格名：" >
              <div  v-for="(item,index) in specificationsData" :key="index" style="margin-bottom:15px">
                  <Input
                  placeholder="请输入商品规格内容 "
                   @input="getskuList"
                  v-model="specificationsData[index]"
                  style="width:270px"
                />
                <Icon class="skuEnabelIcon" type="md-arrow-round-up"  @click="SpecificationsUp(index)"/>
                <Icon class="skuEnabelIcon" type="md-arrow-round-down"  @click="Specificationsdown(index)"/>
                <Icon class="skuEnabelIcon" @click="deleteSpecifications(index)" type="ios-trash-outline" />
              </div>
              <div >
               <span style="color:#2A82E4;font-size:14px;cursor:pointer;" @click="addSpecifications()">+增加规格</span>
                <span class="addClass" v-if="typeName.length==0" @click="addTypeName()">添加类型</span>
              </div>
              
          </FormItem>
          <FormItem label="类型名："  v-if="typeName.length>0">
              <div  v-for="(item,index) in typeName" :key="index" style="margin-bottom:10px">
                  <Input
                  placeholder="请输入商品规格内容 "
                  @input="getskuList"
                  v-model="typeName[index]"
                  style="width:270px"
                />
                <Icon class="skuEnabelIcon" @click="TypeNameUp(index)" type="md-arrow-round-up" />
                <Icon class="skuEnabelIcon" @click="TypeNameDown(index)" type="md-arrow-round-down" />
                <Icon class="skuEnabelIcon" @click="deleteTypeName(index)" type="ios-trash-outline" />
              </div>
              <div style="color:#2A82E4;font-size:14px;cursor:pointer;" @click="addTypeName()">
                + 增加类型
              </div>             
          </FormItem>
           <Divider dashed />
           <div class="specifications">
              <div v-for="(item,index) in form.skuList" class="item" :key="index">
                  <div class="title">
                      {{item.skuName}}<span v-if="item.skuName&&item.typeName"> + </span>{{item.typeName}}
                  </div>
                  <div class='center'>
                      <span>售价：</span>
                        <Input
                          placeholder="售价"
                          v-model="item.price"
                          style="width:100px"
                        />
                         <span style="margin-left:20px;">原价：</span>
                        <Input
                          placeholder="划线价格"
                          v-model="item.originalPrice"
                          style="width:100px"
                        />
                         <span style="margin-left:20px;">库存：</span>
                        <Input
                          placeholder="商品库存"
                          v-model="item.reserve"
                          style="width:100px"
                        />
                        <span style="margin-left:20px;">产品批号：</span>
                        <Input
                          placeholder="产品批号"
                          v-model="item.batchNum"
                          style="width:100px"
                        />
                        <span style="margin-left:20px;">产品编号：</span>
                        <Input
                          placeholder="产品编号"
                          v-model="item.code"
                          style="width:100px"
                        />
                  </div>
              </div>
              
           </div>
           <Divider dashed />
        </template>

        <template v-if="form.skuEnabel!=1">
        <FormItem label="商品规格：" prop="skuName">
                 <Input
                  placeholder="请输入商品规格内容 "
                  v-model="form.skuName"
                  style="width:420px"
                />
        </FormItem>
        <FormItem label="商品售价：" prop="price">
                 <Input
                  placeholder="请输入商品售价"
                  v-model="form.price"
                  style="width:200px"
                />
                <span>原价：</span>
                <Input
                  placeholder="商品原价，划线价格"
                  v-model="form.originalPrice"
                  style="width:200px"
                />
        </FormItem>
        <FormItem label="商品库存：" prop="reserve">
          <Input
                  placeholder="请输入商品库存"
                  v-model="form.reserve"
                  style="width:420px"
                />
        </FormItem>
        </template>
        <FormItem label="商品试样：" prop="sampleEnabel">
            <i-switch size="large" true-value="1" false-value="0" v-model="form.sampleEnabel">
                <span slot="open">开</span>
                <span slot="close">关</span>
            </i-switch>
        </FormItem>
        <template v-if="form.sampleEnabel==1">
         <FormItem label="试样规格：" prop="sampleSkuName">
            <Input  placeholder="请输入试样规格名" v-model="form.sampleSkuName" style="width:420px" />
        </FormItem>
         <FormItem label="试样售价：" prop="samplePrice">
            <Input
                  placeholder="试样售价"
                  v-model="form.samplePrice"
                  style="width:100px"
                />
                <span style="margin-left:20px;">试样库存：</span>
                 <Input
                  placeholder="试样库存"
                  v-model="form.sampleReserve"
                  style="width:100px"
                />
        </FormItem>
        </template>
        <Divider dashed />
        <FormItem label="商品介绍：" prop="title">
          <editor
              ref="editor"
              v-model="form.content"
          
              @on-change="editChange"
            />
             <!-- <editor  ref="editor" v-model="form.content" editorId="content" @on-change="editChange" /> -->
        </FormItem>

        <FormItem>
         
        </FormItem>
      </Form>
      </div>
    
       <div class="footer">
            <Button @click="ModalCancel">取消</Button>
            <Button
              style="margin-left: 10px"
              type="primary"
              @click="getConfirm"
              >确认</Button
            >
        </div>
    </div>
    <!-- <div class="effect">
      <div class="title">广告预览</div>
      <div class="effect-center"></div>
    </div> -->
  </div>
</template>

<script>
import Editor from "_c/editor";
import {apiProducttypeList} from '@/api/classification-manage.js'
import {apiProductInfo,apiProductSave,apiProductAllTag } from '@/api/product-manage.js'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import axios from 'axios';
export default {
  name: 'product-manage',
 components: { Editor ,Treeselect},
  data () {
    return {
      headers: {
        token: localStorage.getItem("token"),
      },
      uploadUrl: process.env.VUE_APP_API_URL + "/upload-file",
      height:0,
      query: {},
      diyDom:{},
      diyData: {},
      form:{
        batchNum:'',
        code:'',
        contentUrl:"",
        createTime:"",
        limitEnabel:'',
        downTime:"",
        id:'',
        img:[],
        video:'',
        liked:'',
        limitNumber:'',
        showSales:'',
        originalPrice:'',
        price:'',
        reserve:'',
        sales:'',
        sampleEnabel:'',
        samplePrice:'',
        sampleReserve:'',
        sampleSkuName: "",
        skuEnabel:'',
        skuList:[],
        skuName: "",
        sort:'',
        status:'',
        tag:"",
        title:"",
        typeId:'',
        upTime:"",
        content:'',
      },
      specificationsData:[],//规格名
      typeName:[],//类型名
      apiData: {
        producttypeList:[],
        productAllTag:[],
      }
    }      
  },
  methods: {
     getDetail(){
        apiProductInfo({id:this.query.id}).then(res=>{
          console.log(res)
          this.form={
            batchNum:res.data.batchNum,
            code:res.data.code,
            contentUrl:res.data.contentUrl,
            createTime:res.data.createTime,
            limitEnabel:res.data.limitEnabel+'',
            downTime:res.data.downTime,
            id:res.data.id,
            img:res.data.img.split(","),
            video:res.data.video,
            liked:res.data.liked,
            limitNumber:res.data.limitNumber,
            originalPrice:res.data.originalPrice,
            price:res.data.price,
            reserve:res.data.reserve,
            sales:res.data.sales,
            sampleEnabel:res.data.sampleEnabel+'',
            samplePrice:res.data.samplePrice,
            sampleReserve:res.data.sampleReserve,
            sampleSkuName: res.data.sampleSkuName,
            skuEnabel:res.data.skuEnabel+'',
            skuList:res.data.skuList,
            skuName:res.data.skuName,
            showSales:res.data.showSales,
            sort:res.data.sort,
            status:res.data.status,
            tag:res.data.tag,
            title:res.data.title,
            typeId:res.data.typeId+'',
            upTime:res.data.upTime,
            content:'',
          }
          var specificationsData=[],typeName=[]
          if(res.data.skuList&&res.data.skuList.length>0){
            res.data.skuList.forEach(element => {
              specificationsData.push(element.skuName)
              if(element.typeName){
                typeName.push(element.typeName)
              }
              
            });
          }
          
          this.specificationsData=Array.from(new Set(specificationsData)) //规格名
          this.typeName=Array.from(new Set(typeName)) //类型名
          if(res.data.contentUrl){
            var contentUrl=res.data.contentUrl
            if (window.location.protocol === "https:") {
               contentUrl = this.replaceAll(res.data.contentUrl, "http://", "https://");
            } else {
               contentUrl = this.replaceAll(res.data.contentUrl, "http://", "https://");
            }
            this.getDetailsConent(contentUrl)
          } 
        })
     },
     replaceAll(str, find, replace) {
        return str.replace(new RegExp(find, 'g'), replace);
      },
     //获取详情富文本
    getDetailsConent:function(contentUrl){
      var that=this
     axios.get(contentUrl+'?a='+Math.round(Math.random()*10)).then(function (response) {
        var html=response.data
        html=html.replace(/<!DOCTYPE html>/g,'')
        html=html.replace(/<html lang="en">/g,'')
        html=html.replace(/<head>/g,'')
        html=html.replace(/<meta charset="utf-8">/g,'')
        html=html.replace(/<meta http-equiv="X-UA-Compatible" content="IE=edge">/g,'')
        html=html.replace(/<meta name="viewport" content="width=device-width">/g,'')
        html=html.replace(/<\/head>/g,'')
        html=html.replace(/<style>\*%7Bmargin:0px;padding:0px;font-size:16px%7Dimg%7Bwidth:100%;display:block25%7D<\/style>/g,'')
        html=html.replace(/<style>\*{margin:0px;padding:0px;font-size:16px}img{width:100%;display:block}<\/style>/g,'')
        html=html.replace(/<body>/g,'')
        html=html.replace(/<xml>/g,'')
        html=html.replace(/<\/xml>/g,'')
        html=html.replace(/<\/body><\/html>/g,'')
        html=html.replace(/<img style="width:100%;display:block"/g,'<img')         
        // that.str=html
        that.form.content=html
        that.$refs.editor.setHtml(html);
      })
      .catch(function (error) {
        console.log(error);
      });
    },
    getProducttypeList(){
        apiProducttypeList().then(res => {
            // var obj=[]
            // for(var i=0;i<res.data.length;i++){
            //     if(res.data[i].level==1){
            //         var data=res.data[i]
            //         data.children=[]
            //         data.label=res.data[i].name
            //         data.isEdit=false
            //         obj.push(data)
            //     }else{
            //         obj=obj.map(item=>{
            //             if(item.id==res.data[i].parentId){
            //                 var children=res.data[i]
            //                 children.isEdit=false
            //                 children.label=res.data[i].name
            //                 item.children.push(children)
            //             }
            //             return item
            //         })
            //     }
               
            // }
            // this.apiData.producttypeList=obj.map(item=>{
            //   if(item.children.length==0){
            //     delete item.children
            //   }
            //  return item
            // })

            this.apiData.producttypeList=res.data
        });
    },
    uploadSuccess(type, res, index = 0) {
      if (res.code != 200) {
        return this.$Modal.error({ title: "提示", content: res.msg });
      }
      this.$Message.success("文件上传成功");
      if(type=='img'){
        this.form.img.push(res.data.fileUrl);
      }else if(type=='video'){
        this.form.video=res.data.fileUrl
      }
      
    },
    // 文件上传失败
    uploadErr() {
      this.$Spin.hide();
      this.$Modal.error({
        title: "提示",
        content: "文件上传失败，请重试",
      });
    },
    // 查看文件
    lookFile(url) {
      const a = document.createElement("a");
      document.body.appendChild(a);
      a.target = "_blank";
      a.href = url;
      a.click();
      document.body.removeChild(a);
    },
    // 删除文件
    deleteFile(type,index) {
      this.$Modal.confirm({
        title: "提示",
        content: "确认删除文件？",
        onOk: () => {
          if(type=='img'){
            this.form.img.splice(index, 1);
          }else if(type=='video'){
            this.form.video=''
          }
          
        },
      });
    },
    editChange(res, text) {
      if (res == "<p><br></p>") {
        this.form.content = text;
        return;
      }
      this.form.content = res;
    },
    addSpecifications(){
      this.specificationsData.push('')
      // this.getskuList()
    },
    deleteSpecifications(index){
      this.specificationsData.splice(index,1)
      this.getskuList()
    },
    SpecificationsUp(index){
      if(index!=0){
        var data=this.specificationsData.map((item,index)=>{
          return item
        })
        this.specificationsData.splice(index, 1, data[index - 1]);
        this.specificationsData.splice(index - 1, 1, data[index]);
      }
    },
    Specificationsdown(index){
      if(index!=this.specificationsData.length-1){
        var data=this.specificationsData.map((item,index)=>{
          return item
        })
        this.specificationsData.splice(index, 1, data[index + 1]);
        this.specificationsData.splice(index + 1, 1, data[index]);
      }
    },
    addTypeName(){
      this.typeName.push('')
    },
     deleteTypeName(index){
      this.typeName.splice(index,1)
      this.getskuList()
    },
    TypeNameUp(index){
      if(index!=0){
        var data=this.typeName.map((item,index)=>{
          return item
        })
        this.typeName.splice(index, 1, data[index - 1]);
        this.typeName.splice(index - 1, 1, data[index]);
        this.getskuList()
      }

    },
    TypeNameDown(index){
      if(index!=this.typeName.length-1){
        var data=this.typeName.map((item,index)=>{
          return item
        })
        this.typeName.splice(index, 1, data[index + 1]);
        this.typeName.splice(index + 1, 1, data[index]);
        this.getskuList()
      }
    },
    getskuList(){
      var data=[]
      var skuList=this.form.skuList
      for(var i=0;i<this.specificationsData.length;i++){
        console.log(this.specificationsData[i])
        if(this.typeName&&this.typeName.length>0){
          for(var j=0;j<this.typeName.length;j++){
              if(this.specificationsData[i]||this.typeName[j]){
                var obj={
                   originalPrice:'',
                  code:'',
                  batchNum:'',
                  price:'',
                  reserve:'',
                  skuName: this.specificationsData[i],
                  typeName: this.typeName[j]
                }
                if(skuList&&skuList.length>0){                 
                  for(var k=0;k<skuList.length;k++){
                    if(skuList[k].skuName==this.specificationsData[i]&&skuList[k].typeName==this.typeName[j]){
                        obj.originalPrice=skuList[k].originalPrice
                        obj.price=skuList[k].price
                        obj.reserve=skuList[k].reserve
                        obj.batchNum=skuList[k].batchNum
                        obj.code=skuList[k].code                   
                    }
                  }
                  data.push(obj)
                }else{
                  data.push(obj)
                }
              }
              
            }
        }else{
           var obj={
                   originalPrice:'',
                  code:'',
                  batchNum:'',
                  price:'',
                  reserve:'',
                  skuName: this.specificationsData[i],
                  typeName: ''
                }
               if(skuList&&skuList.length>0){                 
                  for(var k=0;k<skuList.length;k++){
                    if(skuList[k].skuName==this.specificationsData[i]){
                        obj.originalPrice=skuList[k].originalPrice
                        obj.price=skuList[k].price
                        obj.reserve=skuList[k].reserve
                        obj.batchNum=skuList[k].batchNum
                        obj.code=skuList[k].code                   
                    }
                  }
                  data.push(obj)
                }else{
                  data.push(obj)
                }
        }
        
      }
      this.form.skuList=data

    },

    ModalCancel(){
      this.$router.go(-1)
    },
     getConfirm(){
      if(this.form.content){
          var html='<!DOCTYPE html>'
            html+='<html lang="en">'
            html+='<head>'
            html+='<meta charset="utf-8">'
            html+='  <meta http-equiv="X-UA-Compatible" content="IE=edge">'
            html+='<meta name="viewport" content="width=device-width">'
            html+='</head>'
            html+='<style>*%7Bmargin:0px;padding:0px;font-size:16px%7Dimg%7Bwidth:100%;display:block;25%7D</style>'
            html+='<body>'
            html+=this.form.content
            html+='</body>'
            html+='</html>'
            html=html.replace(/<img/g,'<img style="max-width:100%;display:block;margin:10px auto"')
        }else{
          var html=''
        }   
        console.log(html,this.form)
      var params={...this.form}
      params.id=this.query.id
      params.img=this.form.img.join(',')
      params.content=html
      // return false
      apiProductSave(params).then(res=>{
          if(res.code==200){
            this.$Message.success('保存成功')
            this.$router.push({name:'product-manage'})
          }else{
            this.$Message.error(res.msg)
          }

      })
     },
      //所有标签
    getProductAllTag(){
      apiProductAllTag().then(res => {
        this.apiData.productAllTag=res.data
      });
    },

  },
   mounted () {
    var that=this
    this.query=this.$route.query
    this.$refs.editor.setHtml("");
    setTimeout(() => {
     var height=document.getElementsByClassName('content-wrapper')[0].clientHeight-210
      that.height=height
    }, 500);
    
   
    this.getProducttypeList()
    this.getProductAllTag()
    if(this.query.id){
      this.getDetail()
    }
    
  },
}
</script>

<style scoped lang="less">
.max-w200{
    max-width: 200px;
    width: 100%;
}
.product-center {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .product-left {
    width:100%;
    background: #fff;
    // min-height: 600px;
    padding: 40px;
    box-sizing: border-box;
    margin-right: 20px;
  }
  .product-left-center{
     width:100%;
     height:calc(100% - 100px);
     overflow: hidden;
     overflow-y: auto;
     margin-bottom: 20px;
  }
}
.addClass{
  width: 80px;
  height: 24px;
  opacity: 1;
  border-radius: 2px;
  background: #FFFFFF;
  border: 1px solid rgba(0, 0, 0, 0.15);
  display: inline-block;
  text-align: center;
  line-height: 24px;
  font-size: 14px;
  font-weight: 400;
  letter-spacing: 0px;
  color: rgba(0, 0, 0, 0.65);
  font-size:14px;cursor:pointer;
  margin-left:10px
}
.tag{
  width: 50px;
height: 26px;
opacity: 1;
border-radius: 5px;
background: rgba(255, 87, 51, 1);
text-align: center;
line-height: 26px;
font-size: 14px;
font-weight: 400;
color: rgba(255, 255, 255, 1);
margin-left: 10px;
display: inline-block;
cursor: pointer;
}
.skuEnabelIcon{
  margin-left: 15px;
  font-size: 24px;
  cursor: pointer;
}
.specifications{
  font-size: 14px;
font-weight: 400;
letter-spacing: 0px;
line-height: 20.27px;
color: rgba(56, 56, 56, 1);
text-align: left;
margin-bottom: 10px;
padding-left: 100px;
}
.specifications .item{
  margin-bottom: 15px;
}
.specifications .title{
  margin-bottom: 5px;
}

.pdl10{
  padding-left: 10px;
}
// .footer{
//   position: fixed;
//   bottom: 0px;
//   left: 0px;
//   background: #fff;
//   padding: 20px;
//   box-sizing: border-box;
// }
</style>
 